/**
 * 操作项目信息处理模块
 */
const Sequelize = require('sequelize')
const Op = Sequelize.Op
const sequelize = require('../db/dbconfig')
const ProjectModel = require('../db/models/project_infos')
const ProjectCateModel = require('../db/models/project_cates')
const UserinfoModel = require('../db/models/users')
const TabsModel = require('../db/models/tabs')
const url = require("url");
const fs = require("querystring");
const projectModel = ProjectModel(sequelize)
const projectCateModel = ProjectCateModel(sequelize)
const userinfoModel = UserinfoModel(sequelize)
const tabsModel = TabsModel(sequelize)

// 添加项目模块
exports.addProjectinfo = async (req, res) => {
  try {
    const userId = req.body?.userId;
    const form = req.body?.form;
    // return res.myMsg('test',200)
    // if (info.form.price !== 0) projectinfo.is_open_source = 0;

    let results = await projectModel.create({
      user_id: userId,
      tags: JSON.stringify(form.tags),
      pro_title: form.title,
      pro_biography: form.briefly,
      pro_content: form.desc,
      pro_path: JSON.stringify(form.files),
      price: form.amount,
      is_open_source: form.isPayment,
      pro_cover: form.fileCoverList,
    })
    return res.myMsg(results, 200)
  } catch (e) {
    if (e.name === 'SequelizeValidationError') return res.myMsg(e)
    return res.myMsg(e, 500)
  }
}

// 删除项目模块
exports.delProjectinfo = async (req, res) => {
  try {
    let results = await projectModel.update({
      is_delete: 1
    }, {
      where: {
        pro_id: req.body.id
      }
    })
    if (results[0] === 0) return res.myMsg('项目不存在，删除失败',500)
    return res.myMsg('项目删除成功', 200)
  } catch (e) {
    res.myMsg(e)
  }
}

// 修改项目模块
exports.updateProjectinfo = async (req, res) => {
  try {
    const projectinfo = req.body
    let is_exist = await projectModel.findOne({
      where: {
        is_delete: 0,
        pro_id: projectinfo.pro_id
      }
    })
    if (is_exist === null) return res.myMsg('项目不存在，修改失败')
    if (projectinfo.price !== 0) projectinfo.is_open_source = 0
    let results = await projectModel.update({
      cate_id: projectinfo.cate_id === 0 ? is_exist.cate_id : projectinfo.cate_id,
      tab_ids: projectinfo.tab_ids === '' ? is_exist.tab_ids : projectinfo.tab_ids,
      pro_title: projectinfo.pro_title === '' ? is_exist.pro_title : projectinfo.pro_title,
      pro_biography: projectinfo.pro_biography === '' ? is_exist.pro_biography : projectinfo.pro_biography,
      pro_pic: projectinfo.pro_pic === '' ? projectinfo.pro_pic : projectinfo.pro_pic,
      pro_content: projectinfo.pro_content === '' ? is_exist.pro_content : projectinfo.pro_content,
      pro_path: projectinfo.pro_path === '' ? is_exist.path : projectinfo.pro_path,
      price: projectinfo.price === 0 ? is_exist.price : projectinfo.price,
      is_open_source: projectinfo.is_open_source === 0 ? 0 : 1
    }, {
      where: {
        pro_id: projectinfo.pro_id
      }
    })
    if (results[0] === 0) return res.myMsg('修改失败')
    res.myMsg('修改成功', 200)
  } catch (e) {
    res.myMsg(e)
  }
}
// 根据id改项精选
exports.updateProjectSelectedByProjectId = async (req, res) => {
  try {
    const pro_id = req.body.pro_id;
    const selected = req.body.selected;
    let is_exist = await projectModel.findOne({
      where: {
        is_delete: 0,
        pro_id: pro_id
      }
    })
    if (is_exist === null) return res.myMsg('项目不存在，修改失败', 500)
    let results = await projectModel.update({
      selected: selected,
    }, {
      where: {
        pro_id: pro_id,
      }
    })
    if (results[0] === 0) return res.myMsg('请求成功,无改动', 200);
    return res.myMsg('修改成功', 200)
  } catch (e) {
    res.myMsg(e)
  }
}
// 根据id改项热门
exports.updateProjectHotByProjectId = async (req, res) => {
  try {
    const pro_id = req.body.pro_id;
    const hot = req.body.hot;
    let is_exist = await projectModel.findOne({
      where: {
        is_delete: 0,
        pro_id: pro_id
      }
    })
    if (is_exist === null) return res.myMsg('项目不存在，修改失败', 500)
    let results = await projectModel.update({
      hot: hot,
    }, {
      where: {
        pro_id: pro_id,
      }
    })
    if (results[0] === 0) return res.myMsg('请求成功,无改动', 200);
    return res.myMsg('修改成功', 200)
  } catch (e) {
    res.myMsg(e)
  }
}

// 查询项目信息
exports.getProjectinfoAll = async (req, res) => {
  // const {query} = url.parse(req.url, false);
  // let temp = parseInt(fs.parse(query).offset[0]) || 0
  let offset = 0
  // offset = temp%2===0? temp:temp-1
  try {
    // 关联外键
    projectModel.belongsTo(projectCateModel, {
      // as: 'cate',
      foreignKey: 'cate_id',
      targetKey: 'cate_id'
    })
    projectModel.belongsTo(userinfoModel, {
      // as: 'cate',
      foreignKey: 'user_id',
      targetKey: 'user_id'
    })
    let results = await projectModel.findAndCountAll({
      include: [
        {
          attributes: ['cate_name'],
          // as: 'cate',
          model: projectCateModel,
        }, {
          attributes: ['nickname'],
          // as: 'cate',
          model: userinfoModel,
        }
      ],
      where: {
        is_delete: 0
      },
      order: [
        ['pro_id', 'asc']
      ],
      // limit: 10,
      offset,
      // raw:true
    })
    if (results === '') return res.myMsg('查询错误')
    // let create_at = moment(results.rows.creation_time).format("'YYYY-MM-DD HH:mm:ss'");
    // let update_at = moment(results.rows.update_time).format("'YYYY-MM-DD HH:mm:ss'");
    // const data = { ...results,creation_time: create_at, update_time: update_at  }
    // console.log(results)
    // res.myMsg(results,0)
    // res.type('text/javascript');
    // res.send({
    //   data: JSON.stringify(
    //     results
    //   )
    // })
    results = { status: 200, ...results }
    res.type('application/json');
    res.jsonp(results);
    // res.myMsg(results,200)
  } catch (e) {
    res.myMsg(e)
  }
}

// 根据项目id查询项目信息
exports.getProjectinfoByProId = async (req, res) => {
  try {
    // 关联外键
    projectModel.belongsTo(userinfoModel, {
      // as: 'cate',
      foreignKey: 'user_id',
      targetKey: 'user_id'
    })
    const pro_id = req.body.id;
    let results = await projectModel.findOne({
      include: [
        {
          attributes: ['username'],
          model: userinfoModel,
        }
      ],
      where: {
        is_delete: 0,
        pro_id: pro_id,
      },
    })
    if (results === null || results === '') return res.myMsg('查询失败,不存在该项目', 404)
    console.log('res', results)
    // res.type('application/json');
    // res.jsonp(results);
    res.myMsg(results, 200)
  } catch (e) {
    res.myMsg(e)
  }
}

// 模糊查询 项目标题
exports.getProjectinfoByTitle = async (req, res) => {
  try {
    const projectinfo = req.body.data
    // 关联外键
    projectModel.belongsTo(projectCateModel, {
      // as: 'cate',
      foreignKey: 'cate_id',
      targetKey: 'cate_id'
    })
    projectModel.belongsTo(userinfoModel, {
      // as: 'cate',
      foreignKey: 'user_id',
      targetKey: 'user_id'
    })
    let results = await projectModel.findAll({
      include: [
        {
          attributes: ['cate_name'],
          // as: 'cate',
          model: projectCateModel,
        }, {
          attributes: ['nickname'],
          // as: 'cate',
          model: userinfoModel,
        }
      ],
      where: {
        is_delete: 0,
        pro_title: {
          [Op.like]: `%${projectinfo}%`
        }
      },
      // raw: true
    })
    if (results == '') return res.myMsg('查询失败，不存在该项目')
    res.myMsg(results, 200)
  } catch (e) {
    res.myMsg(e)
  }
}
